<!--
  文件描述：用户
  创建时间：2023/9/5 14:58
  创建人：二
-->
<template>
  <div class="m-page-wrap">
    <el-form class="m-search-form" ref="searchForm" :inline="true" :model="searchForm">
      <el-form-item label="姓名" prop="name">
        <el-input v-model="searchForm.name"/>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="handleRefresh(true)">查询</el-button>
        <el-button @click="resetSearchForm()">重置</el-button>
      </el-form-item>
    </el-form>

    <div class="m-table-wrap">
      <div class="m-btn-list">
        <el-button
          type="primary"
          icon="el-icon-plus"
          v-has-permit="['system:user:add']"
          @click="handleAdd()">
          新增
        </el-button>
        <el-button
          type="primary"
          icon="el-icon-download"
          v-has-permit="['system:user:export']"
          @click="handleExport()"
        >
          导出
        </el-button>
        <el-button
          type="primary"
          icon="el-icon-upload2"
          v-has-permit="['system:user:import']"
          @click="handleImport()"
        >
          导入
        </el-button>
      </div>

      <m-table
        :loading="loading"
        :columns="columns"
        :data="tableData"
        row-key="id"
        :page-size.sync="pagination.limit"
        :current-page.sync="pagination.page"
        :total="pagination.total"
        @pagination-change="handleRefresh"
        @sort-change="sortChange"
        @selection-change="selectionChange"
        >

        <template #province="{row}">
          {{ row.address.split(' ')[0] }}
        </template>

        <template #city="data">
          {{ data.row.address.split(' ')[1] }}
        </template>

        <template #action="{ row }">
          <el-link
            type="primary"
            :underline="false"
            v-has-permit="['system:user:watch']"
            @click="handleWatch(row)"
          >
            查看
          </el-link>
          <el-link
            type="primary"
            :underline="false"
            v-has-permit="['system:user:edit']"
            @click="handleEdit(row)"
          >
            编辑
          </el-link>
          <el-link
            type="danger"
            :underline="false"
            v-has-permit="['system:user:remove']"
            @click="handleDelete(row)"
          >
            删除
          </el-link>
        </template>

      </m-table>

    </div>
    <UserAdd ref="userAdd" @success="handleRefresh"/>

    <MImportFile
      ref="MImportFile"
      :templateUrl="templateUrl"
      :importFileApi="importFileApi"
      templateFileName="用户导入模板"
      @success="handleRefresh"
    />
  </div>
</template>

<script>
import UserAdd from './components/add'
import { getUserListApi } from '@/api/system/user.js'
import {
  excelExport
} from 'pikaz-excel-js'
export default {
  name: 'User',
  components: {
    UserAdd
  },
  data() {
    return {
      searchForm: {
        name: ''
      },
      columns: [
        { type: 'selection', width: 60, align: 'center' },
        { label: 'ID', prop: 'id', align: 'center', sortable: true },
        { label: '用户名称', prop: 'name', align: 'center' },
        { label: '邮箱', prop: 'email', align: 'center' },
        { label: '地址', prop: 'address', align: 'center',
          children: [
            { label: '省份', prop: 'province', align: 'center', slotName: 'province' },
            { label: '市区', prop: 'city', align: 'center', slotName: 'city' },
            { label: '地址', prop: 'address', align: 'center' }
          ]
        },
        { label: '操作', prop: 'action', align: 'center', slotName: 'action', width: 220, fixed: 'right' }
      ],
      tableData: [],
      loading: false,
      pagination: {
        page: 1,
        limit: 10,
        total: 0
      },
      templateUrl: '',
      importFileApi: getUserListApi
    }
  },
  created() {},
  activated() {
    this.handleRefresh(this.mixinFirstLoad);
  },
  methods: {
    // 重置搜索表单
    resetSearchForm() {
      this.$refs.searchForm.resetFields();
      this.handleRefresh(true);
    },
    /**
     * 刷新列表
     * @param {Boolean} bool 强制刷新到第一页
     */
    handleRefresh(bool = false) {
      if (bool) this.pagination.page = 1;
      this.mixinFirstLoad = false;
      this.getData();
    },
    // 获取数据
    getData() {
      this.loading = true;
      getUserListApi({
        ...this.searchForm,
        page: this.pagination.page,
        limit: this.pagination.limit
      }).then(res => {
        this.tableData = res.data.list;
        this.pagination.total = res.data.total;
      }).finally(() => {
        this.loading = false;
      })
    },
    /**
     * 监听表格排序
     * @param data
     */
    sortChange(data) {
      console.log(data)
    },
    /**
     * 监听表格选中
     * */
    selectionChange(val) {
      console.log('val;', val)
    },
    // 新增
    handleAdd() {
      this.$refs.userAdd.open()
    },
    // 编辑
    handleEdit(data) {
      this.$refs.userAdd.open('edit', data)
    },
    // 查看
    handleWatch(data) {
      // console.log('data', data)
      this.$router.push({
        path: '/system/user/watch',
        query: {
          id: data.id
        }
      })
    },
    // 删除
    handleDelete() {
      this.mixinMessageBoxConfirm('此操作将删除该数据, 是否继续?').then(({instance, done}) => {
        setTimeout(() => {
          done();
          setTimeout(() => {
            instance.confirmButtonLoading = false;
            this.$message({
              type: 'success',
              message: '删除成功!'
            });
          }, 300);
        }, 2000);
      }).catch(() => {})
    },
    // 导出
    handleExport() {
      const tableData = this.tableData;
      let itemObj = {
        name: '',
        email: '',
        province: '',
        city: '',
        address: ''
      }
      let keys = Object.keys(itemObj)
      let sheet = {
        // 表头
        tHeader: [
          '用户名称',
          '邮箱',
          '地址',
          '',
          ''
        ],
        // 数据键名
        keys,
        // 表格数据
        table: tableData.map(d => {
          let address = d.address.split(' ');
          return {
            ...d,
            province: address[0],
            city: address[1]
          }
        }),
        // 合并项
        merges: [
          '1-1:1-2',
          '2-1:2-2',
          '3-1:5-1'
        ],
        // 单元格样式
        cellStyle: [
          ...(keys.map((d, index) => {
            return {
              cell: `${Number(index) + 1}-1`,
              fill: { fgColor: { rgb: '4F81BD' } },
              font: {
                color: { rgb: 'ffffff' }
              }
            }
          })),
          ...(keys.map((d, index) => {
            return {
              cell: `${Number(index) + 1}-2`,
              fill: { fgColor: { rgb: '4F81BD' } },
              font: {
                color: { rgb: 'ffffff' }
              }
            }
          }))
        ]
      }

      sheet.table.unshift({
        ...itemObj,
        province: '省份',
        city: '市区',
        address: '地址'
      })
      excelExport({
        sheet: [sheet],
        filename: `用户列表${new Date().getTime()}`
      })
    },
    // 导出
    handleImport() {
      this.$refs.MImportFile.open();
    }
  }
}
</script>

<style scoped>

</style>
